package com.xtianzhuang.www.controller.ocr;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.xtianzhuang.www.controller.BaseController;
import com.xtianzhuang.www.entity.request.base.BaseRequest;
import com.xtianzhuang.www.entity.response.PaddleOCRResponse;
import com.xtianzhuang.www.entity.response.base.BaseResponse;

import sun.misc.BASE64Encoder;

/**
 * @author: zhuangxt
 * @createTime: 2024/06/28 10:01
 */
@Controller
@RequestMapping("/ocr")
public class PaddleOCRController extends BaseController {

	@RequestMapping(value = "/use")
	public ModelAndView useOcr(BaseRequest request, BaseResponse response) {
		ModelAndView modelAndView = new ModelAndView();
		super.executeBase(request, response);
		modelAndView.addObject("res", response);
		modelAndView.setViewName("ocr/ocr");
		// 跳回原地址
		return modelAndView;
	}

	@RequestMapping("/upload")
	@ResponseBody
	public PaddleOCRResponse fileUpload(@RequestParam("file") MultipartFile file, HttpServletRequest req) {
		PaddleOCRResponse response = new PaddleOCRResponse();
		String result = "";
		try {
			paddleOcrServiceBiz.checkFile(file);
			// 准备文件夹,获取项目中upload文件夹的路径
			String parentDir = req.getServletContext().getRealPath("upload");
			paddleOcrServiceBiz.checkDir(parentDir);
			// 获取原始文件名
			String originalFilename = file.getOriginalFilename();
			logger.info("\t originalFilename=" + originalFilename);
			// 确定最终保存时使用的文件
			String filename = UUID.randomUUID().toString().replace("-", "");
			String suffix = "";
			int beginIndex = originalFilename.lastIndexOf(".");
			if (beginIndex != -1) {
				suffix = originalFilename.substring(beginIndex);
			}
			// 执行保存文件
			File dest = new File(parentDir + "/ocr/" + filename + suffix);
			file.transferTo(dest);
			blindDateServiceBiz.savePicture(filename, originalFilename, file.getSize(), suffix);
			response.setPicUrl("/web2019/upload/ocr/" + filename + suffix);
			response.setCode("0000");

			RestTemplate restTemplate = new RestTemplate();
			MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
			map.add("images", ImageToBase64(new FileInputStream(new File(parentDir + "/ocr/" + filename + suffix))));

			HttpHeaders headers = new HttpHeaders();
			//设置请求头格式
			//Set the request header format
			headers.setContentType(MediaType.APPLICATION_JSON);
			HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);
			// 发送请求
			Map json = restTemplate.postForEntity("http://127.0.0.1:8868/predict/ocr_system", request, Map.class).getBody();
			logger.error("请求返回的json :\n" + json);
			// 解析Json返回值
			// Parse the Json return value
			List<List<Map>> json1 = (List<List<Map>>) json.get("results");
			// 循环遍历出所有内容
			for (int i = 0; i < json1.get(0).size(); i++) {
				result += json1.get(0).get(i).get("text");
				String rate = json1.get(0).get(i).get("confidence").toString();
//				result += "(相似度:" + rate.substring(2, 4) + "." + rate.substring(4, 6) + "%, 坐标：";
//				List<List<Integer>> json2 = (List<List<Integer>>) json1.get(0).get(i).get("text_region");
//				result += json2 + ")\n";
				result += "/\n";
//				if(i%5==0){
//					result += "<br/>\n";
//				}

			}
			if(result.contains("联通")){
				result="包含联通字样\n<br/>详情如下：<br/>"+result;
			}else{
				result="不包含联通字样\n<br/>详情如下：<br>"+result;

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		response.setMessage(result);
		return response;

	}

	private String ImageToBase64(InputStream imgPath) {
		byte[] data = null;
		// 读取图片字节数组
		// Read the image byte array
		try {
			InputStream in = imgPath;
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		BASE64Encoder encoder = new BASE64Encoder();
//		 System.out.println("图片转换Base64:" + encoder.encode(Objects.requireNonNull(data)));
		return encoder.encode(Objects.requireNonNull(data));
	}


}
